{% extends 'base.html' %}
{% load static %}

{% block title %}每日签到 - 本地有约{% endblock %}

{% block extra_css %}
<style>
    .checkin-card {
        max-width: 600px;
        margin: 2rem auto;
    }
    
    .checkin-status {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
        text-align: center;
    }
    
    .points-badge {
        font-size: 3rem;
        font-weight: bold;
        margin: 1rem 0;
    }
    
    .checkin-btn {
        font-size: 1.2rem;
        padding: 0.8rem 3rem;
        border-radius: 50px;
        border: none;
        background: white;
        color: #667eea;
        font-weight: bold;
        cursor: pointer;
        transition: all 0.3s;
    }
    
    .checkin-btn:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.2);
    }
    
    .checkin-btn:disabled {
        background: #ccc;
        color: #666;
        cursor: not-allowed;
    }
    
    .stats-row {
        display: flex;
        justify-content: space-around;
        margin-top: 1.5rem;
    }
    
    .stat-item {
        text-align: center;
    }
    
    .stat-value {
        font-size: 2rem;
        font-weight: bold;
        display: block;
    }
    
    .stat-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .reward-card {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 1.5rem;
        margin-bottom: 1rem;
    }
    
    .reward-title {
        font-size: 1.1rem;
        font-weight: bold;
        margin-bottom: 1rem;
        color: #333;
    }
    
    .reward-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.8rem;
        background: white;
        border-radius: 8px;
        margin-bottom: 0.5rem;
    }
    
    .reward-item:last-child {
        margin-bottom: 0;
    }
    
    .reward-days {
        font-weight: 500;
        color: #667eea;
    }
    
    .reward-points {
        font-weight: bold;
        color: #f59e0b;
    }
    
    .calendar-card {
        background: white;
        border-radius: 10px;
        padding: 1.5rem;
        margin-top: 2rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    
    .calendar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
    }
    
    .calendar-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 0.5rem;
    }
    
    .calendar-day {
        aspect-ratio: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
        font-size: 0.9rem;
        position: relative;
    }
    
    .calendar-day.header {
        font-weight: bold;
        color: #666;
        background: #f8f9fa;
    }
    
    .calendar-day.checked {
        background: #667eea;
        color: white;
        font-weight: bold;
    }
    
    .calendar-day.today {
        border: 2px solid #667eea;
        font-weight: bold;
    }
    
    .calendar-day.empty {
        background: transparent;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="checkin-card">
        <h2 class="text-center mb-4">
            <i class="fas fa-calendar-check"></i> 每日签到
        </h2>
        
        <!-- 签到状态卡片 -->
        <div class="checkin-status">
            <div class="points-badge" id="totalPoints">{{ user.points }}</div>
            <div class="mb-3">我的积分</div>
            
            <button class="checkin-btn" id="checkinBtn" onclick="doCheckin()">
                <i class="fas fa-hand-pointer"></i> 点击签到
            </button>
            
            <div class="stats-row">
                <div class="stat-item">
                    <span class="stat-value" id="consecutiveDays">0</span>
                    <span class="stat-label">连续天数</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value" id="monthCheckins">0</span>
                    <span class="stat-label">本月签到</span>
                </div>
            </div>
        </div>
        
        <!-- 签到奖励说明 -->
        <div class="reward-card">
            <div class="reward-title">
                <i class="fas fa-gift"></i> 签到奖励规则
            </div>
            <div class="reward-item">
                <span class="reward-days">每日签到</span>
                <span class="reward-points">+5 积分</span>
            </div>
            <div class="reward-item">
                <span class="reward-days">连续3天</span>
                <span class="reward-points">额外 +5 积分</span>
            </div>
            <div class="reward-item">
                <span class="reward-days">连续7天</span>
                <span class="reward-points">额外 +10 积分</span>
            </div>
        </div>
        
        <!-- 签到日历 -->
        <div class="calendar-card">
            <div class="calendar-header">
                <h5 class="mb-0">签到日历</h5>
                <span id="calendarMonth"></span>
            </div>
            <div class="calendar-grid" id="calendarGrid">
                <!-- 日历将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let checkinStatus = {
        hasCheckedIn: false,
        consecutiveDays: 0,
        monthCheckins: 0,
        // @ts-ignore - Django template variable
        totalPoints: {{ user.points|default:0 }}
    };
    
    // 页面加载时获取签到状态
    document.addEventListener('DOMContentLoaded', function() {
        loadCheckinStatus();
        loadCalendar();
    });
    
    // 加载签到状态
    function loadCheckinStatus() {
        fetch('/points/api/checkin/status/')
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    const data = result.data;
                    checkinStatus = data;
                    
                    // 更新页面显示
                    document.getElementById('totalPoints').textContent = data.total_points;
                    document.getElementById('consecutiveDays').textContent = data.consecutive_days;
                    document.getElementById('monthCheckins').textContent = data.month_checkins;
                    
                    // 更新签到按钮状态
                    const btn = document.getElementById('checkinBtn');
                    if (data.has_checked_in) {
                        btn.textContent = '今日已签到';
                        btn.disabled = true;
                        btn.innerHTML = '<i class="fas fa-check-circle"></i> 今日已签到';
                    }
                }
            })
            .catch(error => {
                console.error('加载签到状态失败:', error);
            });
    }
    
    // 执行签到
    function doCheckin() {
        const btn = document.getElementById('checkinBtn');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 签到中...';
        
        fetch('/points/api/checkin/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                // 签到成功
                const data = result.data;
                
                // 显示成功动画和消息
                showSuccess(`签到成功！获得 ${data.points_earned} 积分`);
                
                // 更新显示
                document.getElementById('totalPoints').textContent = data.total_points;
                document.getElementById('consecutiveDays').textContent = data.consecutive_days;
                
                // 更新按钮
                btn.innerHTML = '<i class="fas fa-check-circle"></i> 今日已签到';
                
                // 重新加载日历
                setTimeout(() => {
                    loadCheckinStatus();
                    loadCalendar();
                }, 1000);
                
            } else {
                // 签到失败
                showError(result.message || '签到失败');
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-hand-pointer"></i> 点击签到';
            }
        })
        .catch(error => {
            console.error('签到失败:', error);
            showError('签到失败，请稍后重试');
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-hand-pointer"></i> 点击签到';
        });
    }
    
    // 加载签到日历
    function loadCalendar() {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1;
        
        fetch(`/points/api/checkin/calendar/?year=${year}&month=${month}`)
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    renderCalendar(result.data);
                }
            })
            .catch(error => {
                console.error('加载日历失败:', error);
            });
    }
    
    // 渲染日历
    function renderCalendar(data) {
        const grid = document.getElementById('calendarGrid');
        const monthDisplay = document.getElementById('calendarMonth');
        
        monthDisplay.textContent = `${data.year}年${data.month}月`;
        
        // 清空日历
        grid.innerHTML = '';
        
        // 添加星期标题
        const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
        weekDays.forEach(day => {
            const cell = document.createElement('div');
            cell.className = 'calendar-day header';
            cell.textContent = day;
            grid.appendChild(cell);
        });
        
        // 计算本月第一天是星期几
        const firstDay = new Date(data.year, data.month - 1, 1).getDay();
        
        // 添加空白格子
        for (let i = 0; i < firstDay; i++) {
            const cell = document.createElement('div');
            cell.className = 'calendar-day empty';
            grid.appendChild(cell);
        }
        
        // 获取本月天数
        const daysInMonth = new Date(data.year, data.month, 0).getDate();
        const today = new Date();
        const todayDate = today.getDate();
        const isCurrentMonth = today.getFullYear() === data.year && (today.getMonth() + 1) === data.month;
        
        // 将签到记录转换为日期集合
        const checkedDates = new Set(data.checkins.map(c => c.date));
        
        // 添加日期
        for (let day = 1; day <= daysInMonth; day++) {
            const cell = document.createElement('div');
            cell.className = 'calendar-day';
            cell.textContent = day;
            
            const dateStr = `${data.year}-${String(data.month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            
            if (checkedDates.has(dateStr)) {
                cell.classList.add('checked');
                cell.title = '已签到';
            }
            
            if (isCurrentMonth && day === todayDate) {
                cell.classList.add('today');
            }
            
            grid.appendChild(cell);
        }
    }
    
    // 显示成功消息
    function showSuccess(message) {
        // 可以使用Bootstrap Toast或其他通知组件
        alert(message);
    }
    
    // 显示错误消息
    function showError(message) {
        alert(message);
    }
</script>
{% endblock %}
